<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/6/24
 * Time: 13:44
 */

namespace app\service;

use app\admin\controller\Common;
use Redis\Redis;
use think\Db;
use think\facade\Config;

/**
 * 行业服务层
 * @author   juzi
 * @blog     https://blog.csdn.net/juziaixiao
 * @version  1.0.0
 * @datetime 2020年6月24日13:23:09
 */
class IndustryService
{

    /**
     * 获取行业列表
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function IndustryList($params)
    {

        $where = empty($params['where']) ? [['is_del', '=', 2]] : $params['where'];

        $page = $params['page'] ? true : false;
        $number = isset($params['number']) ? intval($params['number']) : 10;
        $field = empty($params['field']) ? '*' : $params['field'];
        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;

        // 获取列表
        $data = Db::name('industry')->where($where)->field($field)->order('id desc');

        //分页
        $page_html = null;
        if ($page) {
            $data = $data->paginate($number, false, ['query' => request()->param()]);
            $data = $data->toArray()['data'];

        } else {
            $data = $data->limit($m, $n)->select();
        }

        return self::InforDataDealWith($data, $params);

    }

    /**
     * 总数
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param    [array]          $where [条件]
     */
    public static function IndustryTotal($where)
    {
        return (int)Db::name('industry')->where($where)->count();
    }

    /**
     * 数据处理
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $data [原始数据]
     * @param   [array]          $params [输入参数]
     */
    public static function InforDataDealWith($data, $params)
    {

        if (!empty($data)) {
            foreach ($data as &$v) {
                if (isset($params['where']['id'])) {
                    //收益周期
                    $v['cycle_income'] = Db::name('industry_cycleincome')->where('industry_id=' . $v['id'])->select();
                }

                //当前总数量
                $v['total_num'] = Db::name('member_business')->where('industry_id=' . $v['id'] . ' and status <> -1')->count();

                //所属等级 news_accept news_status
                if (isset($v['level'])) {
                    $v['level_id'] = $v['level'];
                    $v['level'] = $v['level'] . '级';

                }


                if (isset($v['status'])) {
                    switch ($v['status']) {
                        case 1:
                            $v['status_desc'] = '运行中';
                            break;
                        case 2:
                            $v['status_desc'] = '已下架';
                            break;
                    }
                }

                // 内容
                if (isset($v['detail'])) {

                    //$v['detail'] = ResourceService::ContentStaticReplace($v['detail'], 'get');
                    if (!empty(get_images_from_html($v['detail']))) {
                        $v['editor_imgs'] = join(',', get_images_from_html($v['detail']));
                    }


                }

                // 图片
                if (isset($v['logo'])) {
                    if (!empty($v['logo'])) {
                        $img = ResourceService::AttachmentPathViewHandle($v['logo'], true);

                        $v['logo'] = $img;
                    }
                }

            }
        } else {
            return DataReturn('未获取到数据', -1, $data);
        }

        return DataReturn('获取成功', 0, $data);


    }


    /**
     * 消息保存
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日15:37:22
     * @desc    description
     * @param    [array]          $params [输入参数]
     *
     * public static function IndustrySave($params = [])
     * {
     * // 请求参数
     * $p = [
     * [
     * 'checked_type'      => 'empty',
     * 'key_name'          => 'news_title',
     * 'error_msg'         => '名称不能为空',
     * 'error_code'         => 30002,
     * ],
     * [
     * 'checked_type'      => 'empty',
     * 'key_name'          => 'news_author',
     * 'error_msg'         => '发布人不能为空',
     * 'error_code'         => 30003,
     * ],
     * [
     * 'checked_type'      => 'empty',
     * 'key_name'          => 'news_accept',
     * 'error_msg'         => '接收人不能为空',
     * 'error_code'         => 30004,
     * ],
     *
     * [
     * 'checked_type'      => 'empty',
     * 'key_name'          => 'news_sendtime',
     * 'error_msg'         => '发送时间不能为空',
     * 'error_code'         => 30005,
     * ],
     * [
     * 'checked_type'      => 'empty',
     * 'key_name'          => 'news_thumb',
     * 'error_msg'         => '缩略图不能为空',
     * 'error_code'         => 30006,
     * ],
     *
     * ];
     * # 添加是判断标题是否重复
     * if(empty($params['id'])){
     * $p[]=   [
     * 'checked_type'      => 'unique',
     * 'checked_data'      => 'news',
     * 'key_name'          => 'news_title',
     * 'error_msg'         => '名称不能重复',
     * 'error_code'         => 30001,
     * ];
     * }
     *
     * $ret = ParamsChecked($params, $p);
     *
     * if($ret !== true)
     * {
     * $error_arr=explode(',',$ret);
     *
     * //throw new BaseException(['code'=>403 ,'errorCode'=>20001,'msg'=>'分类名称不能重复','status'=>false,'data'=>null]);
     * return json(DataReturn($error_arr[0], $error_arr[1]));
     * }
     * $data=$params;
     *
     * // 添加/编辑
     * if(empty($params['id']))
     * {
     *
     * $data['news_create'] = date("Y-m-d H:i:s");
     * return  self::MassInfo($params,$data);
     * } else {
     *
     * $data['news_update'] = date("Y-m-d H:i:s");
     *
     * if(Db::name('news')->where(['id'=>intval($params['id'])])->update($data))
     * {
     * $id = $params['id'];
     * }
     * return json(DataReturn('保存成功', 0));
     * }
     *
     *
     *
     * }
     */

    /**
     * 列表条件
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日15:37:22
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function IndustryListWhere($params = [])
    {

        $where = [];
        if (!empty($params['title'])) {
            $where[] = ['title', 'like', '%' . $params['title'] . '%'];
        }
        $where[] = ['is_del', '=', 2];
        return $where;
    }


    /**
     * 级别列表条件
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日15:37:22
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function LevelsListWhere($params = [])
    {

        $where = [];
        if (!empty($params['title'])) {
            $where[] = ['title', 'like', '%' . $params['title'] . '%'];
        }
        $where[] = ['level', '>', '1'];
        return $where;
    }


    /**
     * 级别总数
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param    [array]          $where [条件]
     */
    public static function LevelsTotal($where)
    {
        return (int)Db::name('member_level')->where($where)->count();
    }


    /**
     * 获取级别列表
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public static function LevelsList($params)
    {

        $where = empty($params['where']) ? [['id', '>', 0]] : $params['where'];

        $page = $params['page'] ? true : false;
        $number = isset($params['number']) ? intval($params['number']) : 10;
        $field = empty($params['field']) ? '*' : $params['field'];
        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;


        // 获取列表
        $data = Db::name('member_level')->where($where)->field($field)->order('id asc');

        //分页
        //$page_html=null;
        if ($page) {
            $data = $data->paginate($number, false, ['query' => request()->param()]);

            // $page_html=$data->render();

            $data = $data->toArray()['data'];

        } else {
            $data = $data->limit($m, $n)->select();
        }
        //$params['page_html']=$page_html;


        return DataReturn('获取成功', 0, $data);

    }

    /**
     * 名称重复判断
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月28日09:56:02
     * @desc    description
     * @param   [array]          $params [输入参数]
     */
    public function CheckTitle($params)
    {


        $data = Db::name($params['table'])->where($params['where'])->find();

        if (!empty($data) && empty($params['params']['id'])) {
            if ($data['is_del']) {

            }
            throw new \BaseException(['code' => 403, 'errorCode' => $params['error_code'], 'msg' => $params['msg'], 'status' => false, 'debug' => false]);

        }

        if (!empty($data) && isset($params['params']['id']) && intval($data['id']) != $params['params']['id']) {

            throw new \BaseException(['code' => 403, 'errorCode' => $params['error_code'], 'msg' => $params['msg'], 'status' => false, 'debug' => false]);
        }

        return true;
    }


    /**
     * 等级保存
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function SaveLe($params)
    {

//        self::VaryLe($params);

        Db::startTrans();
        // 添加/编辑
        $data = [];
        $data['trade_num'] = $params['trade_num'];
        $data['share_num'] = $params['share_num'];
        $data['team_people'] = $params['team_people'];
        $data['integral'] = $params['integral'];
        $data['consumption_amount'] = $params['consumption_amount'];
        $data['recharge_times'] = $params['recharge_times'];
        $data['goldfinish'] = $params['goldfinish'];
        $data['is_limits'] = $params['is_limits'] == 'on' ? 2 : 1;


        // 编辑
        $re = Db::name('member_level')->where(['id' => intval($params['id'])])->update($data);
//        if (!$re)
//        {
//            throw new \BaseException(['code'=>403 ,'errorCode'=>50000,'msg'=>'升级设置失败','status'=>false,'data'=>null,'debug'=>false]);
//
//        }

        if ($data['is_limits'] == 2) {
            //执行级别设置添加
            $insert_data = [];
            foreach ($params['member_level'] as $k => $v) {

                $insert_data[$k]['level_id'] = $params['id'];
                $insert_data[$k]['member_level'] = $v;
                $insert_data[$k]['member_num'] = $params['member_num'][$k];

            }


            Db::name('industry_level_limits')->where('level_id=' . $params['id'])->delete();
            $ret = Db::name('industry_level_limits')->insertAll($insert_data);
            if (!$ret) {
                Db::rollback();
                throw new \BaseException(['code' => 403, 'errorCode' => '30008', 'msg' => '删除行业级别队员信息失败', 'status' => false, 'debug' => false]);
            }
        }

        Db::commit();
        return true;


    }

    /**
     * 行业级别数据校验
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function VaryLe($params)
    {

        // 请求参数
        $p = [

            [
                'checked_type' => 'empty',
                'key_name' => 'trade_num',
                'error_msg' => '交易数不能为空',
                'error_code' => 50003,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'team_people',
                'error_msg' => '团队内人数不能为空',
                'error_code' => 50004,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'share_num',
                'error_msg' => '直推人数不能为空',
                'error_code' => 50005,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'integral',
                'error_msg' => '所需积分不能为空',
                'error_code' => 50006,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'integral',
                'error_msg' => '必须为大于0整数',
                'error_code' => 5007,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'share_num',
                'error_msg' => '必须为大于0整数',
                'error_code' => 5007,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'team_people',
                'error_msg' => '必须为大于0整数',
                'error_code' => 5007,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'trade_num',
                'error_msg' => '必须为大于0整数',
                'error_code' => 5007,
            ],
        ];

        $ret = ParamsChecked($params, $p);

        if (true !== $ret) {
            $error_arr = explode(',', $ret);
            throw new \BaseException(['code' => 403, 'errorCode' => $error_arr[0], 'msg' => $error_arr[1], 'status' => false, 'data' => null, 'debug' => false]);
            //return json(DataReturn($error_arr[0], $error_arr[1]));
        }

        return true;
    }

    /**
     * 行业数据校验
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function VaryData($params)
    {
        // 请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'title',
                'error_msg' => '名称不能为空',
                'error_code' => 30002,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'logo',
                'error_msg' => '缩略图不能为空',
                'error_code' => 30003,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'min_worth',
                'error_msg' => '基础价值不能为空',
                'error_code' => 30004,
            ],

            [
                'checked_type' => 'empty',
                'key_name' => 'max_worth',
                'error_msg' => '最高价值不能为空',
                'error_code' => 30005,
            ],

            [
                'checked_type' => 'env_number',
                'key_name' => 'min_worth',
                'error_msg' => '必须为大于0',
                'error_code' => 30011,
            ],

            [
                'checked_type' => 'env_number',
                'key_name' => 'max_worth',
                'error_msg' => '必须为大于0',
                'error_code' => 30011,
            ],
        ];

        $ret = ParamsChecked($params, $p);

        if (true !== $ret) {

            //$error_arr[0]  $error_arr[1]
            $error_arr = explode(',', $ret);
            throw new BaseException(['code' => 403, 'errorCode' => $error_arr[1], 'msg' => $error_arr[0], 'status' => false, 'debug' => false]);
        }

        //名称重复判断
        $check_data = [
            'where' => [['title', '=', $params['title']], ['is_del', '=', 2]],
            'table' => 'industry',
            'params' => $params,
            'msg' => '名称不能重复',
            'error_code' => 30001,
        ];
        IndustryService::CheckTitle($check_data);

        //阶段值判断
        foreach ($params['cycle_min'] as $k => $v) {
            //不能小于0
            if ($v <= 0 || $params['cycle_income'][$k] <= 0 || $params['cycle_day'][$k] <= 0 || $params['cycle_max'][$k] <= 0) {
                throw new \BaseException(['code' => 403, 'errorCode' => 30012, 'msg' => '阶段数值必须大于0', 'status' => false, 'debug' => false]);
            }
            //阶段内最小值判断
            if ($v < $params['min_worth']) {
                throw new \BaseException(['code' => 403, 'errorCode' => 30013, 'msg' => '阶段最小值不得小于行业最小值', 'status' => false, 'debug' => false]);
            }
            //阶段最大值判断
            if ($params['cycle_max'][$k] > $params['max_worth']) {
                throw new \BaseException(['code' => 403, 'errorCode' => 30014, 'msg' => '阶段最大值不得大于行业最大值', 'status' => false, 'debug' => false]);
            }
            if ($params['cycle_max'][$k] < $v) {
                throw new \BaseException(['code' => 403, 'errorCode' => 30015, 'msg' => '阶段最大值不得小于阶段内最小值', 'status' => false, 'debug' => false]);
            }
        }

        //处理多余图片
        $in_use = get_images_from_html($params['detail']);
        $in_all = explode(',', $params['editor_imgs']);
        if (is_array($in_use) && is_array($in_all)) {
            Common::DelRemainder($in_use, $in_all);
        }
        return true;

    }

    /**
     * 行业数据处理
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function HandleData($params)
    {
        $data = $params;

        //删除多余字段
        unset($data['thumb_img']);
        unset($data['cycle_min']);
        unset($data['cycle_max']);
        unset($data['cycle_id']);
        unset($data['cycle_day']);
        unset($data['cycle_income']);
        unset($data['editor_imgs']);
        $data['logo'] = str_replace('/upload/', '', $data['logo']);
        return $data;
    }

    /**
     * 行业保存
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日11:08:21
     * @param    [array]          $params [输入参数]
     */
    public static function SaveInd($data, $params)
    {
        Db::startTrans();
        // 添加/编辑
        if (empty($params['id'])) {
            $industry_id = Db::name('industry')->insertGetId($data);
            if (!$industry_id) {
                Db::rollback();
                throw new \BaseException(['code' => 403, 'errorCode' => '30006', 'msg' => '添加行业失败', 'status' => false, 'debug' => false]);
            }
        } else {
            $data['update_time'] = date("Y-m-d H:i:s");
            $industry_id = $params['id'];
            $old_data = Db::name('industry')->where(['id' => intval($params['id'])])->field('title,logo')->find();
            $re = Db::name('industry')->where(['id' => intval($params['id'])])->update($data);
            if (!$re) {
                Db::rollback();
                throw new \BaseException(['code' => 403, 'errorCode' => '30007', 'msg' => '修改行业失败', 'status' => false, 'debug' => false]);
            }
            //修改用户行业信息
            $member_industry_data = [];
            if ($old_data['title'] != $data['title']) {
                $member_industry_data['industry_title'] = $data['title'];
            }
            if ($old_data['logo'] != $data['logo']) {
                $member_industry_data['industry_imgurl'] = $data['logo'];
            }
            if (count($member_industry_data) > 0) {
                $re = Db::name('member_business')->where(['industry_id' => intval($params['id'])])->update($member_industry_data);
//                if (!$re) {
//                    Db::rollback();
//                    throw new \BaseException(['code' => 403, 'errorCode' => '30007', 'msg' => '修改用户行业失败', 'status' => false, 'debug' => false]);
//                }
            }
        }

        //执行行业收益周期添加
        $insert_data = [];

        foreach ($params['cycle_min'] as $k => $v) {

            $insert_data[$k]['industry_id'] = $industry_id;
            $insert_data[$k]['min_num'] = $v;
            $insert_data[$k]['max_num'] = $params['cycle_max'][$k];
            $insert_data[$k]['cycle_period'] = $params['cycle_day'][$k];
            $insert_data[$k]['day_income'] = $params['cycle_income'][$k];
        }
        //dump($insert_data);exit;

        Db::name('industry_cycleincome')->where('industry_id=' . $industry_id)->delete();
        $ret = Db::name('industry_cycleincome')->insertAll($insert_data);
        if (!$ret) {
            Db::rollback();
            throw new \BaseException(['code' => 403, 'errorCode' => '30008', 'msg' => '保存行业收益周期失败', 'status' => false, 'debug' => false]);
        }
        Db::commit();
        $_redis = new Redis();
        $_redis->hDel("levelSection", $params['level']);
        return true;
    }

    public static function DodelInd($params)
    {
        $id = $params['id'];
        $id = explode(',', $id);
        $where_busines = [
            ['industry_id', 'in', $id],
            ['status', '<>', 5],
        ];
        $member_business = Db::name('member_business')->where($where_busines)->count();
        if ($member_business > 0) {
            return json(DataReturn('行业正在占用中', '30009'));
        }


        $where_del = [['id', 'in', $id]];
        $sql = Db::name('industry')->where($where_del);
        $cates = $sql->field('category')->select();
        foreach ($cates as $v) {
            if ($v['category'] != 1) {
                return json(DataReturn('默认行业无法删除', '30011'));
            }
        }

        Db::startTrans();
        $re = Db::name('industry')->where($where_del)->update(['is_del' => 1]);
        if (!$re) {
            Db::rollback();
            return json(DataReturn('删除行业失败', '30010'));
        }
        Db::commit();
    }
}